﻿#if UNITY_EDITOR

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace AI.Graph.Editor {


    public class NodeContextEvent : GraphEvent {

        private GenericMenu m_menu;


        public override void OnProcess (Event e) {
            if (m_menu != null) {
                m_menu.ShowAsContext ();
                m_menu = null;
            }

            if (e.IsMouseDown (MouseButton.Right) && e.IsMouseInsideRect (canvas.unscaledRect)) {
                for (int i = 0; i < canvas.nodes.Length; i++) {
                    Node currentNode = canvas.nodes[i];

                    if (currentNode.isHidden) {
                        continue;
                    }
                    
                    if (currentNode.rect.Contains (canvas.mousePosition)) {

                        for (int j = 0; j < currentNode.ports.Length; j++) {
                            if (currentNode.ports[j].rect.Contains (canvas.mousePosition)) {
                                return;
                            }
                        }
                        
                        m_menu = new GenericMenu ();

                        // save variables
                        Node node = currentNode;
                        AIController controller = graph.controller;
                        NodeRestoreData restoreData = Serializer.CreateNodeRestoreData (node);


                        // Add remove item if its not entry or any state.
                        // Else add disabled remove item.
                        if (node.IsEntryState () || node.IsAnyState ()) {
                            m_menu.AddDisabledItem (new GUIContent ("Delete"), false);
                        }
                        else {
                            m_menu.AddItem (new GUIContent ("Delete"), false, () => {
                                GraphUndo.RecordAndPerform ("Delete node [" + node.name + "]",
                                    () => { Serializer.RemoveNodeFromController (controller, node, false); },
                                    () => { Serializer.RestoreNodeToController (controller, node, restoreData); });
                            });
                        }

                        // Add remove all connections item if the node has connections.
                        // Else add disabled remove all connections item.

                        // calculate connection count and save old connections.
                        int connectionsCount = 0;
                        Dictionary<ConnectionPort, ConnectionPort[]> oldConnections = new Dictionary<ConnectionPort, ConnectionPort[]> ();
                        foreach (ConnectionPort port in node.ports) {
                            connectionsCount += port.connectionCount;
                            oldConnections.Add (port, port.connectedPorts);
                        }

                        string itemName = connectionsCount > 1 ? "Remove all connections" : "Remove connection";

                        if (connectionsCount == 0) {
                            m_menu.AddDisabledItem (new GUIContent (itemName), false);
                        }
                        else {
                            m_menu.AddItem (new GUIContent (itemName), false, () => {
                                GraphUndo.RecordAndPerform (itemName + " from node [" + node.name + "]",
                                    () => { Serializer.DisconnectAllPorts (node); },
                                    () => {
                                        foreach (ConnectionPort fromPort in oldConnections.Keys) {
                                            foreach (ConnectionPort toPort in oldConnections[fromPort]) {
                                                Serializer.ConnectPorts (fromPort, toPort);
                                            }
                                        }
                                    });
                            });
                        }
                        
                        e.Use ();
                    }
                }
            }
        }

    }


}
#endif